#ifdef _WIN32

#include <time.h>
#include "Timing.h"

typedef unsigned long int mulong;
// -----------------------------------------------------------------------
Timing::Timing():lastTick(0),elapsedTime(0.0),paused(true)
{
#ifdef WIN32
        LARGE_INTEGER freq;
        if ( QueryPerformanceFrequency(&freq) && ( freq.QuadPart >= 1000 ) )
        {

        }
#else
#endif
    lastTick = static_cast<mulong>( getSystemTime() );
}
// -----------------------------------------------------------------------
Timing::~Timing()
{

}
// -----------------------------------------------------------------------
void Timing::pause()
{
    paused = true;
    elapsedTime = 0.0;
}
// -----------------------------------------------------------------------
void Timing::resume()
{
    paused = false;
    elapsedTime = 0.0;
    lastTick = static_cast<mulong>( getSystemTime() );
}
// -----------------------------------------------------------------------
void Timing::tick(void)
{
#if WIN32
    static const double clockDivide = 1.0 / (double) CLOCKS_PER_SEC;

    if( paused ) return;

    double now = getSystemTime();

    elapsedTime = ( now - lastTick ) * clockDivide;
    lastTick = static_cast<mulong>( now );
#else
    double now = getSystemTime();
    elapsedTime = ( now - lastTick ) * 1.0;
    lastTick = static_cast<mulong>( now );
#endif
}
// -----------------------------------------------------------------------
double Timing::getElapsedTime()
{
    return paused ? 0.0 : getMilliseconds()*0.001;
}
// -----------------------------------------------------------------------
double Timing::getMilliseconds()
{
#ifdef 	WIN32
    return getSystemTime() - lastTick;
#else
    return (getSystemTime() - lastTick)*1000;
#endif
}
// -----------------------------------------------------------------------
Timing& Timing::getInstance()
{
    static Timing theTiming;
    return theTiming;
}
// -----------------------------------------------------------------------
double Timing::getSystemTime()
{
#ifdef WIN32
        LARGE_INTEGER freq;
        if ( QueryPerformanceFrequency(&freq) )
        {
            LARGE_INTEGER counter;
            QueryPerformanceCounter( &counter );
            if ( freq.QuadPart >= 1000 )
            {
                static const double invQuadPart = 1.0/double(freq.QuadPart);
                // scales by 1000 to have milisecond precision
                double ticks = 1000.0*counter.QuadPart;
                return ticks*invQuadPart;
            }
        }
#else
        if(true)
        {
        	timespec ts;
        	clock_gettime(CLOCK_REALTIME, &ts); //

        	return (ts.tv_sec)/1.0 + (ts.tv_nsec)/1000000000.0;
        	//return (ts.tv_nsec)*1.e-6;
        }
#endif

        const static double divisor   = 1.0 / ((double)CLOCKS_PER_SEC *0.001);
        return (mulong)((double)(clock()) * divisor );
}
// -----------------------------------------------------------------------

#endif
